package com.example.wenhua.config;

import com.example.wenhua.utils.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

/**
 * JWT认证拦截器
 * 拦截需要认证的请求，验证JWT token
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 处理OPTIONS预检请求
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        
        // 获取请求路径
        String requestURI = request.getRequestURI();
        
        // 放行登录接口和静态资源
        if (requestURI.contains("/login") || 
            requestURI.contains("/register") ||
            requestURI.contains("/static") ||
            requestURI.contains("/favicon.ico")) {
            return true;
        }
        
        // 获取token
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            sendErrorResponse(response, 401, "未提供有效的认证token");
            return false;
        }
        
        // 提取实际的token（去掉"Bearer "前缀）
        token = token.substring(7);
        
        // 验证token
        if (!jwtUtil.validateToken(token)) {
            sendErrorResponse(response, 401, "token无效或已过期");
            return false;
        }
        
        // 检查token是否过期
        if (jwtUtil.isTokenExpired(token)) {
            sendErrorResponse(response, 401, "token已过期");
            return false;
        }
        
        // 将用户信息存储到request中，供后续使用
        String username = jwtUtil.getUsernameFromToken(token);
        Integer role = jwtUtil.getRoleFromToken(token);
        request.setAttribute("username", username);
        request.setAttribute("role", role);
        
        return true;
    }
    
    /**
     * 发送错误响应
     */
    private void sendErrorResponse(HttpServletResponse response, int status, String message) throws Exception {
        response.setStatus(status);
        response.setContentType("application/json;charset=UTF-8");
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", status);
        result.put("message", message);
        result.put("data", null);
        
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonResult = objectMapper.writeValueAsString(result);
        response.getWriter().write(jsonResult);
    }
}